ReactJS Ultra For Beginners
🪝 Custom Hooks
What are Custom Hooks?
- Functions that start with "use" and can call other hooks
- Allow you to extract component logic into reusable functions
- Share stateful logic between components
- Keep components clean and focused
📝 Basic Syntax
import { useState, useEffect } from "react"; // Custom hook function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const reset = () => setCount(initialValue); return { count, increment, decrement, reset }; } // Usage in component function Counter() { const { count, increment, decrement, reset } = useCounter(10); return ( <div> <p>Count: {count}</p> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> <button onClick={reset}>Reset</button> </div> ); }
🔑 Naming Convention
✅ Good:
function useCounter() {} function useLocalStorage() {} function useWindowSize() {} function useDebounce() {}
❌ Bad:
function counter() {} function getCounter() {} function useCounterHook() {}
🎯 Common Custom Hooks
1. useLocalStorage:
function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); const setValue = (value) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error(error); } }; return [storedValue, setValue]; } // Usage function UserProfile() { const [user, setUser] = useLocalStorage("user", null); return ( <div> {user ? ( <p>Welcome, {user.name}!</p> ) : ( <button onClick={() => setUser({ name: "John" })}>Login</button> )} </div> ); }
2. useWindowSize:
function useWindowSize() { const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight, }); useEffect(() => { function handleResize() { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); } window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return windowSize; } // Usage function ResponsiveComponent() { const { width, height } = useWindowSize(); return ( <div> <p> Window size: {width} x {height} </p> {width < 768 && <p>Mobile view</p>} </div> ); }
3. useDebounce:
function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value, delay]); return debouncedValue; } // Usage function SearchInput() { const [searchTerm, setSearchTerm] = useState(""); const debouncedSearchTerm = useDebounce(searchTerm, 500); useEffect(() => { if (debouncedSearchTerm) { // Perform search searchAPI(debouncedSearchTerm); } }, [debouncedSearchTerm]); return ( <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Search..." /> ); }
4. useFetch:
function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { setLoading(true); const response = await fetch(url); const result = await response.json(); setData(result); } catch (err) { setError(err); } finally { setLoading(false); } }; fetchData(); }, [url]); return { data, loading, error }; } // Usage function UserList() { const { data: users, loading, error } = useFetch("/api/users"); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; if (!users) return <div>No users found</div>; return ( <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }
🔧 Advanced Patterns
Hook with Parameters:
function useToggle(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = () => setValue(!value); const setTrue = () => setValue(true); const setFalse = () => setValue(false); return { value, toggle, setTrue, setFalse }; } // Usage function ToggleButton() { const { value, toggle } = useToggle(false); return <button onClick={toggle}>{value ? "ON" : "OFF"}</button>; }
Hook with Callbacks:
function useInterval(callback, delay) { const savedCallback = useRef(); useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { if (delay !== null) { const id = setInterval(() => savedCallback.current(), delay); return () => clearInterval(id); } }, [delay]); } // Usage function Timer() { const [count, setCount] = useState(0); useInterval(() => { setCount((c) => c + 1); }, 1000); return <div>Count: {count}</div>; }
Composing Hooks:
function useUser(userId) { const { data: user, loading, error } = useFetch(`/api/users/${userId}`); const [userPreferences, setUserPreferences] = useLocalStorage( `user-${userId}-preferences`, {} ); return { user, userPreferences, setUserPreferences, loading, error, }; }
⚠️ Rules of Custom Hooks
- Always start with "use" - React uses this to identify hooks
- Only call hooks at the top level - not inside loops, conditions, or nested functions
- Only call hooks from React functions - not regular JavaScript functions
- Return values consistently - same structure every time
- Handle cleanup - use useEffect cleanup functions when needed
🎯 Best Practices
- Keep hooks focused - one concern per hook
- Use descriptive names - make the purpose clear
- Handle edge cases - null checks, error handling
- Document your hooks - explain parameters and return values
- Test your hooks - write tests for complex logic
- Reuse existing hooks - compose hooks when possible
111 / 111 videos100% complete
Course Completed!
Great job! You've finished all videos.
Welcome to the Course
Intro to The Course
3:33How to Learn This Course
3:02What is React and Why You Should Learn It?
4:14Getting Started with React
Installing Nodejs
3:03Setting up a React Development Environment
4:30VSCode Extensions
3:17JavaScript Refresher - All JS You Need To Know Before React
Functions
5:39Ternary and Logical Operators
7:21Objects and Arrays
7:11Map and Filter Functions
7:15Array Function Key Prop
3:13String Templating
4:27Basic React Concepts
React Project Folder Structure
6:55An Intro To JSX
10:33What is the App Component?
2:46How to use Components?
10:23Lists in React
9:45CSS in React
9:10Component Project - Build A Simple Website
First React Project
3:34Making A Navbar
7:11Displaying Images
7:11Making the About Us Section
2:35Creating A Footer
3:38Intro To States In React
What is the useState Hook?
10:38What is the useState Hook? Part 2
4:42What is the useState Hook? Part 3
14:50Intro React Project - Task Tracker App
Beginner Project - Task Tracker App
35:03React Component Lifecycle
The Virtual Dom
1:50React Component Lifecycle
1:42The useEffect Hook
15:40The useEffect Hook Part 2
8:41Routing in React
React Router
14:05React Router Part 2
14:28Advanced Forms In React
Forms in React - React Hook Form
25:36State Management
Intro To State Management - Global States
18:37Beginner Project - Build A Blog App
Intermediate Project - Build A Blog App
40:40Intermediate Project - Build A Blog App Part 2
26:57Other Useful React Hooks
Rules of Hooks
4:05Learn the useReducer Hook
9:54Learn the useRef Hook
12:03Making Your Own Custom Hook
12:10